package control;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Queue;

import server.EchoServer;
import server.mysqlConnection;

/**
 * @author MENASHE
 * This class responsible for the operation Return A Book, when the client wants to activate this operation he inserts data in the GUI client
 * , the data we insert into array string that will send to the server, In the server we maps the message by checking the first string (see AbstractControl).
 **/

public class ReturnControl extends AbstractControl {

	private String bid,copy;
	public Object anlyze(String[] msg) 
	{
		bid=msg[1];
		copy=msg[2];
		ArrayList<Object> s=new ArrayList<Object>();
		s.add("Return");
		if(!checkExist())
		{
			s.add("Error: Book does not exist!");
			return s;
		}
		else if(!isBorrwed(msg[1],msg[2]))
		{
			s.add("Error: the book is not borrowed!");
			return s;
		}
		String query2,query1;
		Queue<Integer> q;
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		Calendar cal = Calendar.getInstance();
		String today = new String("'");
		today += dateFormat.format(cal.getTime());
		today += "'";
		q=EchoServer.bookOrdersQueue.get(Integer.parseInt(bid));

		if(q.size()>0)
		{
			EchoServer.sendEmailNotification(getEmail(q.element().toString()),"The book you ordered is now waiting for you in the library.");	
			query1=new String("UPDATE test.borrow SET returnDate="+today+" WHERE bId="+bid+" AND copy="+copy+";");
			Integer sid=q.poll();

			mysqlConnection.update("INSERT into saveorderlist SET sid="+sid+", bid="+bid+", copy="+copy+", date="+today+";"); 
			mysqlConnection.update("DELETE FROM orders WHERE sid="+sid+" AND bid="+bid+";");		
			mysqlConnection.update("UPDATE orders SET indexinqueue=indexinqueue-1 WHERE bid="+bid+";");
			String sid2=getSid();
			mysqlConnection.update("UPDATE test.borrow SET returnDate="+today+" WHERE bId="+bid+" AND copy="+copy+";");
			try {
				if (isGraduatedStudent(sid2,(getGraduationDate( sid2 )))	&&	!hasMoreBorrows(sid2))
				{
					lockAccount(sid.toString());
				}
			} catch (ParseException e) {
				s.add("FAIL");
				return s;
			}
			logActivity(sid.toString(),"The book \""+getNameBook(bid)+"\", bid="+bid+", copy="+copy+" has been returned.");
		}
		
		else
		{
			String sid=getSid();
		
			if(sid.equals("FAIL"))
			{
				s.add("FAIL");
				return s;
				
			}


			
			query2=new String("UPDATE test.books SET isborrowed=0, expectedreturndate=NULL WHERE bid="+msg[1]+" AND copy="+msg[2]+";");
			mysqlConnection.update("UPDATE test.borrow SET returnDate="+today+" WHERE bId="+bid+" AND copy="+copy+";");
			s.add(mysqlConnection.update(query2));
			logActivity(sid,"The book \""+getNameBook(bid)+"\", bid="+bid+", copy="+copy+" has been returned.");
			try {
				if (!hasMoreBorrows(sid) && isGraduatedStudent(sid,(getGraduationDate( sid ))))
				{
					lockAccount(sid);
				}
			} catch (ParseException e) {
				s.add("FAIL");
				return s;
			}
			
		}
			
		
		

		s.add("1");
		return s;
	}



	/**Uses class variables "bid" and "copy" to find the sid of the subscriber that has this specific book
	 * @return sid of the subscriber that currntly has this book borrowed, or "FAIL" if no one has this book.
	 */
	public String getSid()
	{
		String query=new String("select sId FROM test.borrow WHERE bId="+bid+" AND copy="+copy+" AND returnDate=\"00/00/00\";");
		String[][] rst=mysqlConnection.select(query,1);
		if(rst.length==0||rst[0][0].equals("FAIL"))
			return "FAIL";
		else return rst[0][0];

	}

	
	
	/** checks if the book is borrowed
	 * @param bid
	 * @param copy
	 * @return true if the book is borrowed, or flase if it isn't.
	 */
	public static boolean isBorrwed(String bid,String copy)
	{
		String key=new String("Select returnDate from borrow WHERE bid=" +bid+" AND copy="+copy);
		String[][] rst=mysqlConnection.select(key,1);
		if(rst.length!=0)
		{
			for(int i=0;i<rst.length;i++)
			{
				if(rst[i][0].compareTo("00/00/00")==0)
					return true;
			}
		}
			
		return false;
		
	}
	
	/* (non-Javadoc)
	 * @see control.AbstractControl#checkExist()
	 */
	public Boolean checkExist() 
	{
		String rst=mysqlConnection.check("select * from books WHERE bid="+bid+" AND copy="+copy);
		if(rst.length()==0|| rst.compareTo("FAIL")==0) 
			return false;
		return true;
	}
	

	

	
	
	/** checks weather a subscriber has any more borrows
	 * @param sid
	 * @return true if the subscriber has more borrows, or false if he hasn't
	 */
	public boolean hasMoreBorrows(String sid)
	{
		String key=new String("Select count(*) from test.borrow WHERE sid="+sid+" AND returnDate=\"00/00/00\" GROUP BY sid;");
		String[][] rst=mysqlConnection.select(key,1);
		if(rst.length==0 || rst[0][0].equals("FAIL") )
			return false;
		return (!rst[0][0].equals("0"));		
	}
	

	/** changes subscriber's reader card status to "Locked".
	 * @param sid
	 * @return "1" if the status was changed successfully, or "FAIL" if it wasn't
	 */
	public String lockAccount(String sid)
	{
		String query=new String("UPDATE test.subscriber SET CardStatus=0 WHERE sId="+sid+";");
		return(mysqlConnection.update(query));
	}

}